package com.yj.text_pixel;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yj.text_pixel.bean.TextBean;
import com.yj.text_pixel.util.Painter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/** TextPixelPlugin */
public class TextPixelPlugin implements FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    Painter.instance().init(flutterPluginBinding.getApplicationContext());

    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "text_pixel");
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    switch (call.method){
      case "getPlatformVersion":
        result.success("Android " + android.os.Build.VERSION.RELEASE);
        break;
      case "getTextColors":
        int width = call.argument("width");
        int height = call.argument("height");
        List<Map<String, Object>> textList = call.argument("textList");
        int fontSize = call.argument("fontSize");
        int maxFrames = call.argument("maxFrames");
        int maxLines = call.argument("maxLines");
        boolean continuousPaint = call.argument("continuousPaint");
        boolean horizontalCenter = call.argument("horizontalCenter");
        List<TextBean> textBeanList = new ArrayList<>();
        int len = textList.size();
        for(int i = 0; i < len; i++){
          textBeanList.add(JSONObject.parseObject(JSONObject.toJSONString(textList.get(i)),
                  TextBean.class));
        }
        HashMap<String, Object> map = Painter.instance().getTextColors(width, height, textBeanList,
                fontSize, maxFrames, maxLines, continuousPaint, horizontalCenter);
        result.success(map);
        break;
      default:
        result.notImplemented();
        break;
    }
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
    channel = null;
  }
}
